﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sireass.Bl.Security;
using Sireass.Bl;
using Telerik.Web.UI;
using System.Configuration;

namespace Sireass.Asp.Masters
{
    public partial class SiteMasterPage : System.Web.UI.MasterPage
    {
		#region Page
        protected void Page_Load(object sender, EventArgs e)
        {
			if (!IsPostBack)
			{
				bool security = Convert.ToBoolean(ConfigurationManager.AppSettings["Security"]);
				if (security)
				{
					AplicarSeguridad();
				}
			}
			
		}
		#endregion

		#region Métodos
		protected void AplicarSeguridad()
		{
			var identity = HttpContext.Current.User.Identity;
			if (identity.IsAuthenticated)
			{
				radMnuSireass.Visible = true;
				SireassIdentity id = (SireassIdentity)Csla.ApplicationContext.User.Identity;
				List<string> servicios = obtenerServicios(id);
				ValidarMenu(radMnuSireass, servicios);
				lblUsuario.Text = "Bienvenido(a) " + id.FullName;
			}
			else
			{
				radMnuSireass.Visible = false;
			}
		}
		protected List<string> obtenerServicios(SireassIdentity id)
		{
			List<string> servicios = new List<string>();
			foreach (string rol in id.Roles)
			{
				PerfilServicioCriteria criteria = new PerfilServicioCriteria(rol, null, true);
				PerfilServicioList psl = PerfilServicioList.GetPerfilServicioList(criteria);
				foreach (PerfilServicioInfo psi in psl)
				{
					if (!servicios.Contains(psi.Servicio))
					{
						servicios.Add(psi.Servicio);
					}
				}
			}
			return servicios;
		}
		protected void ValidarMenu(RadMenu menu, List<string> servicios)
		{
			for (int i = 0; i < menu.Items.Count; i++)
			{
				RadMenuItem item = menu.Items[i];
				var value = item.Value;
				if (!string.IsNullOrEmpty(value) && !servicios.Contains(value))
				{
					menu.Items[i].Visible = false;
				}
				else if (item.Items.Count > 0)
				{
					ValidarOpcionesMenu(item, servicios);
				}
			}
		}
		protected void ValidarOpcionesMenu(RadMenuItem item, List<string> servicios)
		{
			for (int j = 0; j < item.Items.Count; j++)
			{
				var innerValue = item.Items[j].Value;
				if (!string.IsNullOrEmpty(innerValue) && !servicios.Contains(innerValue))
				{
					item.Items[j].Visible = false;
				}
			}
		}
		#endregion
	}
}